
import { createRouter, createWebHistory } from 'vue-router'

import { routes } from './routes'
import { showErrorMessage } from '@/utils/message';
import { refreshToken } from '@/service/user/userService'; // 假设你已经在 userService 中实现了 refreshToken 方法

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 路由前置路由
router.beforeEach(async (to, from, next) => {
  let accessToken = localStorage.getItem('accessToken')!;
  const reToken = localStorage.getItem('refreshToken');

  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!accessToken) {
      if (reToken) {
        try {
          const response = await refreshToken(reToken as string); // 非空断言
          accessToken = response.accessToken;
          localStorage.setItem('accessToken', accessToken);
          next();
        } catch (error) {
          showErrorMessage('请先登录');
          next('/user');
        }
      } else {
        showErrorMessage('请先登录');
        next('/user');
      }
    } else {
      next();
    }
  } else {
    next();
  }
});
export default router
